/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
     int size(ListNode* l)
     {
         int count=0;
        while(l)
        {
          count++;
          l=l->next;
        }
        return count;
     }
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {

        //特殊的情况

        if(l1==nullptr)
        {
            return l2;
        }
        if(l2==nullptr)
        {
            return l1;
        }


        int L1size=size(l1),L2size=size(l2);//节点个数
        
        ListNode* longL=l1;
        ListNode* shortL=l2;


        if(L1size<L2size)
        {
            longL=l2;
            shortL=l1;

        }
        ListNode* ret =longL;

        int carry=0;//进位
        ListNode *prev=longL;
        while(longL&&shortL)
        {
            int number=longL->val+shortL->val+carry;//求和

            longL->val=number%10;
            carry=number/10;//求进位数
            //迭代
            prev=longL;
            longL=longL->next;
            shortL=shortL->next;
        }

        //最后进位可能是一个巨大的数字
        while(carry)
        {
            if(longL==nullptr)
            {
                  while(carry)
                  {
                    prev->next=new ListNode(carry%10);
                    prev=prev->next;
                    carry/=10;
                  }
            }
            else 
            {
                   int number = longL->val+carry;
                   longL->val=number%10;
                   carry=number/10;
                   prev=longL;
                   longL=longL->next;

            }
          
        }

       return  ret;
    }
};
